local jieyun = fk.CreateSkill {
  name = "ym2__jieyun",
  tags = { Skill.Compulsory },
}

Fk:loadTranslationTable{
  ["ym2__jieyun"] = "解愠",
  [":ym2__jieyun"] = "锁定技，当有伤害被减少或防止后，你摸一张牌；若当前回合角色不为你，你多摸一张牌并交给其一张牌。",
  ["#ym2__jieyun-give"] = "解愠：交给 %dest 一张牌",

  ["$ym2__jieyun1"] = "仁惠百姓，抚爱士卒。",
  ["$ym2__jieyun2"] = "君子务本，本立而道生。",
}

jieyun:addEffect(fk.DamageFinished, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(jieyun.name) then
      if data.prevented or not data.dealtRecorderId then return true end
      if data.extra_data and data.extra_data.ym2__jieyun_maxDamage then
        return data.damage < data.extra_data.ym2__jieyun_maxDamage
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if room.current == player then
      player:drawCards(1, jieyun.name)
    else
      player:drawCards(2, jieyun.name)
      if player.dead or player:isNude() or room.current.dead then return end
      local card = room:askToCards(player, {
        min_num = 1,
        max_num = 1,
        include_equip = true,
        skill_name = jieyun.name,
        --pattern = tostring(Exppattern{ id = cards }),
        prompt = "#ym2__jieyun-give::"..room.current.id,
        cancelable = false,
      })
      if #card > 0 then
        room:moveCardTo(card, Card.PlayerHand, room.current, fk.ReasonGive, jieyun.name, nil, false, player)
      end
    end
  end,
})

jieyun:addEffect(fk.AfterSkillEffect, {
  can_refresh = function (self, event, target, player, data)
    return player.seat == 1
  end,
  on_refresh = function(self, event, target, player, data)
    local e = player.room.logic:getCurrentEvent():findParent(GameEvent.Damage, true)
    if e then
      local dat = e.data
      dat.extra_data = dat.extra_data or {}
      dat.extra_data.ym2__jieyun_maxDamage = dat.extra_data.ym2__jieyun_maxDamage or 0
      dat.extra_data.ym2__jieyun_maxDamage = math.max(dat.damage, dat.extra_data.ym2__jieyun_maxDamage)
    end
  end,
})

jieyun:addEffect(fk.SkillEffect, {
  can_refresh = function (self, event, target, player, data)
    return player.seat == 1
  end,
  on_refresh = function(self, event, target, player, data)
    local e = player.room.logic:getCurrentEvent():findParent(GameEvent.Damage, true)
    if e then
      local dat = e.data
      dat.extra_data = dat.extra_data or {}
      dat.extra_data.ym2__jieyun_maxDamage = dat.extra_data.ym2__jieyun_maxDamage or 0
      dat.extra_data.ym2__jieyun_maxDamage = math.max(dat.damage, dat.extra_data.ym2__jieyun_maxDamage)
    end
  end,
})

return jieyun
